<script setup lang="ts">
import { computed, defineProps, defineEmits, PropType, ref, watchEffect, unref } from 'vue'
import { getDataItems } from '/@/utils/data'
import { ElSelect } from 'element-plus'
import { omit } from 'lodash-es'

const props = defineProps({
  ...ElSelect.props,
  options: { type: Array as PropType<SelectMakerOption[]> },
  dataSource: { type: String },
  hasAll: { type: Boolean, default: false },
})

const emits = defineEmits(['update:modelValue'])


const propsRaw = computed(() => (omit(props, ['options', 'dataSource'])))
const renderOptions = ref<SelectMakerOption[]>([])

const value = ref()
const allowRender = ref(false)
const select = computed(() => {
  return Array.isArray(renderOptions.value) ? renderOptions.value.find(s => s.value == unref(value)) : []
})

const placeholder = computed(() => {
  return props.placeholder || select.value?.label
})

const setRenderOptions = (options: SelectMakerOption[]) => {
  if (props.hasAll) {
    options = [{ label: '全部', value: void 0 }, ...options]
  }
  renderOptions.value = options
}

watchEffect(() => {
  if (props.options && props.options.length) {
    setRenderOptions(props.options as SelectMakerOption[])
    allowRender.value = true
  } else if (props.dataSource) {
    getDataItems(props.dataSource).then(items => {
      setRenderOptions(items as SelectMakerOption[])
    }).finally(() => {
      allowRender.value = true
    })
  } else {
    throw new Error(`SelectMaker：options和dataSouece必须有一个不为空！`)
  }

  value.value = props.modelValue
})


const handChange = (val: any) => {
  emits('update:modelValue', val)
}
</script>


<template>
  <el-select v-model="value" v-bind="propsRaw" @change="handChange" :placeholder="placeholder">
    <el-option v-for="item of renderOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
  </el-select>
</template>